#include "aiai/aiai_fileread.hpp"

aiai_fileread::aiai_fileread(std::string fileName)
{
    filename = fileName;
    isfirstread = true;
    fp = nullptr;
    filelen = 0;
}

aiai_fileread::~aiai_fileread()
{
    if(fp != nullptr)
    {
        close();
    }
}

int aiai_fileread::read(unsigned char *buff, int size, long long index)
{
    if(isfirstread == true)
    {
        fp = fopen(filename.c_str(), "rb");
        if( nullptr == fp ){
            printf("open file error!\n");
            return -1;
        }
        fseek(fp,0,SEEK_END); //定位到文件末
        filelen = ftell(fp); //文件长度
        fseek(fp,0,SEEK_SET);
        isfirstread = false;
    }
    if(index == -1)
    {
        int ret = fread(buff, sizeof(unsigned char), size, fp);
        if(ret < 0){
                printf("read data error!\n");
                return -1;
        }
        return ret;
    }
    else
    {
        fseek(fp,index,SEEK_SET);
        int ret = fread(buff, sizeof(unsigned char), size, fp);
        if(ret < 0){
                printf("read data error!\n");
                return -1;
        }
        return ret;
    }
}

long aiai_fileread::getfilelen()
{
    return filelen;
}

void aiai_fileread::close()
{
    fclose(fp);
    fp = nullptr;
    isfirstread = true;
}
